/*
 * @Author: DUST
 * @Date: 2023-06-26 10:26:55
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-26 10:36:06
 * @FilePath: \national-standard-platform-alarm-screen\src\utils\ckThree\dragControls.js
 * @Description: 
 * undefined
 */
import {
  TransformControls
} from 'three/examples/jsm/controls/TransformControls.js';
import {
  DragControls
} from 'three/examples/jsm/controls/DragControls.js';
/**
 * @description: 创建拖拽控制器
 * @param {*} scene：场景
 * @param {*} renderer：渲染器
 * @param {*} camera：相机
 * @param {*} controls：控制器
 * @return {*}
 */
const initDragControls = (modelContainer, scene, renderer, camera, control, callbackOptions = {
  hoveronCallBack: (event) => event,
  hoveroffCallBack: (event) => event,
  dragstartCallBack: (event) => event,
  dragendCallBack: (event) => event,
}) => {
  // 添加平移控件
  // const transformControls = new TransformControls(camera, renderer.domElement);
  // scene.add(transformControls);
  // transformControls.setMode('translate');
  // transformControls.setMode('rotate');
  // 过滤不是 Mesh 的物体,例如辅助网格
  const objects = [];
  for (let i = 0; i < scene.children.length; i++) {
    if (scene.children[i].isMesh) {
      objects.push(scene.children[i]);
    }
  }
  // 初始化拖拽控件
  const dragControls = new DragControls(modelContainer, camera, renderer.domElement);

  // 鼠标略过事件
  dragControls.addEventListener('hoveron', (event) => {
    // //控件对象transformControl与选中的对象object绑定
    // transformControls.attach(event.object);
    control.enabled = false;
    console.log(event);
    if (event.object.type == "Mesh") event.object.material.emissive.set(0xaaaaaa);
    else if (event.object.type == "Sprite") {
      const scale = event.object.scale;
      event.object.scale.set(scale.x + 1, scale.y + 1, scale.z + 1);
    }
    if (callbackOptions.hoveronCallBack) callbackOptions.hoveronCallBack(event);
  });
  // 鼠标离开事件
  dragControls.addEventListener('hoveroff',
    (event) => {

      if (event.object.type == "Mesh") event.object.material.emissive.set(0x000000);
      else if (event.object.type == "Sprite") {
        const scale = event.object.scale;
        event.object.scale.set(scale.x - 1, scale.y - 1, scale.z - 1);
      }
      control.enabled = true;
      if (callbackOptions.hoveroffCallBack) callbackOptions.hoveroffCallBack(event);
    });
  // 开始拖拽
  dragControls.addEventListener('dragstart', (event) => {
    console.log(event);
    if (callbackOptions.dragstartCallBack) callbackOptions.dragstartCallBack(event);
  });
  // 拖拽结束
  dragControls.addEventListener('dragend', (event) => {
    console.log(event.object.position);
    if (callbackOptions.dragendCallBack) callbackOptions.dragendCallBack(event);
  });

  return dragControls
}

export default initDragControls;